package com.abu.gateway.auth;

import cn.hutool.core.util.StrUtil;
import com.abu.gateway.utils.manager.ManagerJwtUtils;
import com.abu.gateway.utils.portal.JwtProperties;
import com.abu.gateway.utils.portal.PortalJwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthGatewayFilter implements GatewayFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private ManagerJwtUtils managerJwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取request对象和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        获取消息头
        HttpHeaders headers = request.getHeaders();
        List<String> tokenList = headers.get("token");

//        防止Csrf（防止盗链）
        List<String> referList = headers.get("Referer");
        String referer = referList.get(0);
        if (StrUtil.isBlank(referer) || !referer.startsWith("http://localhost")) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        判断token列表是否为空
        if (CollectionUtils.isEmpty(tokenList)) {
            log.info("网关拦截 token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String crToken = tokenList.get(0);
//        判断token是否为空
        if (StrUtil.isBlank(crToken)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        前台用户登录判断->token是以UserLogin开头
        if (StringUtils.startsWith(crToken, "UserLogin")) {
            String userLoginToken = StringUtils.substringAfter(crToken, "UserLogin");
//        解析是否成功
            Boolean flag = PortalJwtUtils.parserToken(userLoginToken, jwtProperties.getPublicKey());
            if (!flag) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } else {
//        后台管理员登录判断->token是以ManagerLogin开头
            String managerToken = StringUtils.substringAfter(crToken, "ManagerLogin");
//        解析是否成功
            try {
                managerJwtUtils.verifyToken(managerToken);
            } catch (Exception e) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
//        3.放行
        return chain.filter(exchange);
    }
}
